package pl.rzarajczyk.breaktime;

import pl.rzarajczyk.breaktime.utils.Utils;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.UIManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

/**
 *
 * @author rzarajczyk
 */
public class Main {

    private static Log log = LogFactory.getLog(Main.class);
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            log.info("Starting the application");
            String lookAndFeelName = UIManager.getSystemLookAndFeelClassName();
            UIManager.setLookAndFeel(lookAndFeelName);
            log.info("Look-and-Feel set to " + lookAndFeelName);

            BeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
            Menu menu = (Menu) factory.getBean("menu");
            factory.getBean("break-window");
            new Main().tray(menu);
            log.info("Application started!");
        } catch (Throwable e) {
            Utils.error(null, log, "Error during running the applicartion", e);
        }
    }

    private void tray(final Menu menu) throws AWTException, IOException, InterruptedException {
        int count = BreakTimeSettings.TRAY_INITIALIZATION_COUNT;
        while ( !SystemTray.isSupported() && count > 0 ) {
            log.warn("SystemTray is not available. Retrying in " + BreakTimeSettings.TRAY_INITIALIZATION_INTERVAL + " ms (" + count + ")");
            Thread.sleep(BreakTimeSettings.TRAY_INITIALIZATION_INTERVAL);
            count--;
        }
        
        if ( ! SystemTray.isSupported() )
            throw new UnsupportedOperationException("SystemTray is not available in your system");

        URL rsrcUrl = Main.class.getResource("/tray-icon.png");
        Image image = ImageIO.read(rsrcUrl);

        TrayIcon tray = new TrayIcon(image, "Break time!", null);
        tray.setToolTip("Break time!");
        tray.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                menu.setLocation( e.getLocationOnScreen() );
                if ( e.getButton() == MouseEvent.BUTTON1 ) {
                    menu.invokeDefaultAction(e);
                } else  if ( e.getButton() == MouseEvent.BUTTON3 ) {
                    menu.setLocation(e.getX(), e.getY());
                    menu.setVisible(true);
                }
            }


        });
        
        SystemTray.getSystemTray().add(tray);
    }
}
